export class Node<T> {
  data: T;
  next: Node<T> | null;
  constructor(data: T) {
    this.data = data;
    this.next = null;
  }
}

export class LinkedList<T> {
  length: number;
  head: Node<T> | null;
  constructor() {
    this.length = 0;
    this.head = null;
  }

  append(data: T) {
    const newNode = new Node<T>(data);
    if (this.length === 0) {
      this.head = newNode;
    } else {
      let currentNode = this.head as Node<T>;
      while (currentNode.next) {
        currentNode = currentNode.next;
      }
      currentNode.next = newNode;
    }
    this.length++;
  }

  insert(position: number, data: T) {
    if (position < 0 || position > this.length) return false;
    const newNode = new Node<T>(data);
    if (position === 0) {
      newNode.next = this.head;
      this.head = newNode;
    } else {
      let index = 0;
      let currentNode = this.head as Node<T>;
      let previousNode = null;
      while (index++ < position) {
        previousNode = currentNode;
        currentNode = currentNode.next as Node<T>;
      }
      newNode.next = currentNode;
      previousNode!.next = newNode;
    }
    this.length++;
    return newNode;
  }

  getData(position: number) {
    if (position < 0 || position >= this.length) return null;
    let index = 0;
    let currentNode = this.head as Node<T>;
    while (index++ < position) {
      currentNode = currentNode.next as Node<T>;
    }
    return currentNode.data;
  }

  indexOf(data: T) {
    let index = 0;
    let current = this.head;
    while (current) {
      if (current.data === data) return index;
      current = current.next;
      index++;
    }
    return -1;
  }

  update(position: number, data: T) {
    if (position < 0 || position >= this.length) return false;
    let index = 0;
    let current = this.head as Node<T>;
    while (index++ < position) {
      current = current.next as Node<T>;
    }
    current.data = data;
    return current;
  }

  removeAt(position: number) {
    if (position < 0 || position >= this.length) return null;

    let current = this.head as Node<T>;
    //
    if (position === 0) {
      this.head = current.next;
    } else {
      let index = 0;
      let previous: Node<T> | null = null;
      while (index++ < position) {
        previous = current;
        current = current.next as Node<T>;
      }
      previous!.next = current.next;
    }
    this.length--;
    return current;
  }

  remove(data: T) {
    return this.removeAt(this.indexOf(data));
  }

  isEmpty() {
    return this.length === 0;
  }

  size() {
    return this.length;
  }

  toString() {
    let current = this.head;
    let result = "";
    while (current) {
      result += current.data + (current.next ? " -> " : "");
      current = current.next;
    }
    return result;
  }
}
